import { Request, Response, NextFunction } from 'express';
import { prisma } from '../../config/database';
import { BaseController } from '../../utils/autoBind';
import { ResponseUtils } from '../../utils/responseUtils';
import { FloorStatus, PerformanceStatus } from '@prisma/client';
import config from '@/config';

/**
 * 客户端楼层控制器
 * 提供楼层信息的查询功能，不包含管理功能
 */
export class ClientFloorController extends BaseController {
  
  /**
   * 获取楼层列表
   * 支持按场馆筛选和分页
   */
  async getFloorList(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { page = 1, limit = 20, venueId, status = FloorStatus.ACTIVE } = req.query;
      const pageNum = parseInt(page as string);
      const limitNum = parseInt(limit as string);
      const skip = (pageNum - 1) * limitNum;

      // 构建查询条件
      const where: any = {
        status: status as FloorStatus
      };
      
      // 如果指定了场馆ID，则按场馆ID筛选
      if (venueId) {
        const venueIdNum = parseInt(venueId as string);
        if (isNaN(venueIdNum)) {
          return ResponseUtils.sendError(res, { code: 400, message: '无效的场馆ID' });
        }
        where.venueId = venueIdNum;
      }

      // 查询楼层列表
      const [items, total] = await Promise.all([
        prisma.floor.findMany({
          where,
          skip,
          take: limitNum,
          orderBy: [
            { level: 'asc' },
            { name: 'asc' }
          ],
          select: {
            id: true,
            venueId: true,
            venue: {
              select: {
                id: true,
                name: true,
                description: true,
                address: true,
                city: true,
                country: true,
                status: true
              }
            },
            name: true,
            level: true,
            description: true,
            floorPlanUrl: true,
            status: true,
            createdAt: true,
            updatedAt: true,
            // 关联的演出信息
            performances: {
              where: { status: PerformanceStatus.SCHEDULED },
              select: {
                id: true,
                title: true,
                startTime: true,
                endTime: true,
                status: true,
                artist: {
                  select: {
                    id: true,
                    name: true,
                    avatar: true
                  }
                }
              },
              orderBy: { startTime: 'asc' }
            }
          }
        }),
        prisma.floor.count({ where })
      ]);

      // 格式化返回数据
      const formattedItems = items.map((floor) => ({
        id: floor.id,
        venueId: floor.venueId,
        venue: floor.venue.name,
        venueInfo: floor.venue,
        name: floor.name,
        level: floor.level,
        description: floor.description,
        floorPlanUrl: floor.floorPlanUrl ? `${config.server.appUrl}${floor.floorPlanUrl}` : null,
        status: floor.status,
        createdAt: floor.createdAt,
        updatedAt: floor.updatedAt,
        performanceCount: floor.performances.length,
        artist: floor.performances[0]?.artist ? {
          id: floor.performances[0].artist.id,
          name: floor.performances[0].artist.name,
          avatar: floor.performances[0].artist.avatar ? `${config.server.appUrl}${floor.performances[0].artist.avatar}` : null
        } : null,
        upcomingPerformances: floor.performances
          .filter((p: any) => new Date(p.startTime) > new Date())
          .slice(0, 3) // 只返回最近的3场演出
      }));
      

      ResponseUtils.paginated(res, formattedItems, total, pageNum, limitNum, '获取楼层列表成功');
    } catch (error) {
      next(error);
    }
  }

  /**
   * 获取楼层详情
   * 包含楼层基本信息、场馆信息、演出信息等
   */
  async getFloorDetail(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { id } = req.params;
      const floorId = parseInt(id);

      if (isNaN(floorId)) {
        return ResponseUtils.sendError(res, { code: 400, message: '无效的楼层ID' });
      }

      const floor = await prisma.floor.findUnique({
        where: { 
          id: floorId,
          status: FloorStatus.ACTIVE
        },
        select: {
          id: true,
          venueId: true,
          venue: {
            select: {
              id: true,
              name: true,
              description: true,
              address: true,
              city: true,
              country: true,
              status: true,
              capacity: true
            }
          },
          name: true,
          level: true,
          description: true,
          floorPlanUrl: true,
          status: true,
          createdAt: true,
          updatedAt: true,
          // 关联的演出信息
          performances: {
            where: { status: PerformanceStatus.SCHEDULED },
            select: {
              id: true,
              title: true,
              description: true,
              startTime: true,
              endTime: true,
              status: true,
              maxCapacity: true,
              currentAttendance: true,
              artist: {
                select: {
                  id: true,
                  name: true,
                  avatar: true,
                  description: true
                  // 移除不存在的 genre 字段
                }
              }
            },
            orderBy: { startTime: 'asc' }
          }
        }
      });

      if (!floor) {
        return ResponseUtils.sendError(res, { code: 404, message: '楼层不存在或已禁用' });
      }

      // 格式化返回数据
      const formattedFloor = {
        ...floor,
        venueId: floor.venueId,
        venue: floor.venue.name,
        venueInfo: floor.venue,
        performanceCount: floor.performances.length,
        upcomingPerformances: floor.performances.filter((p: any) => new Date(p.startTime) > new Date()),
        pastPerformances: floor.performances.filter((p: any) => new Date(p.endTime) < new Date()),
        ongoingPerformances: floor.performances.filter((p: any) => {
          const now = new Date();
          return new Date(p.startTime) <= now && new Date(p.endTime) >= now;
        })
      };

      ResponseUtils.success(res, formattedFloor, '获取楼层详情成功');
    } catch (error) {
      next(error);
    }
  }

  /**
   * 按场馆获取楼层列表
   * 用于场馆详情页面显示该场馆的所有楼层
   */
  async getFloorsByVenue(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { venueId } = req.params;
      const { status = FloorStatus.ACTIVE } = req.query;

      if (!venueId) {
        return ResponseUtils.sendError(res, { code: 400, message: '场馆ID不能为空' });
      }

      const venueIdNum = parseInt(venueId);
      if (isNaN(venueIdNum)) {
        return ResponseUtils.sendError(res, { code: 400, message: '无效的场馆ID' });
      }

      // 首先验证场馆是否存在
      const venue = await prisma.venue.findUnique({
        where: { id: venueIdNum, status: 'ACTIVE' },
        select: {
          id: true,
          name: true,
          description: true,
          address: true,
          city: true,
          country: true
        }
      });

      if (!venue) {
        return ResponseUtils.sendError(res, { code: 404, message: '场馆不存在或已停用' });
      }

      const floors = await prisma.floor.findMany({
        where: {
          venueId: venueIdNum,
          status: status as FloorStatus
        },
        orderBy: [
          { level: 'asc' },
          { name: 'asc' }
        ],
        select: {
          id: true,
          venueId: true,
          venue: {
            select: {
              id: true,
              name: true,
              description: true,
              address: true,
              city: true,
              country: true
            }
          },
          name: true,
          level: true,
          description: true,
          floorPlanUrl: true,
          status: true,
          // 关联的演出信息（简化版）
          performances: {
            where: { status: PerformanceStatus.SCHEDULED },
            select: {
              id: true,
              title: true,
              startTime: true,
              endTime: true,
              status: true
            },
            orderBy: { startTime: 'asc' }
          }
        }
      });

      // 格式化返回数据
      const formattedFloors = floors.map((floor) => ({
        ...floor,
        venueId: floor.venueId,
        venue: floor.venue.name,
        performanceCount: floor.performances.length,
        hasActivePerformances: floor.performances.some((p: any) => p.status === PerformanceStatus.SCHEDULED)
      }));

      ResponseUtils.success(res, {
        venue: venue.name,
        venueInfo: venue,
        floors: formattedFloors,
        totalFloors: formattedFloors.length
      }, '获取场馆楼层列表成功');
    } catch (error) {
      next(error);
    }
  }

  /**
   * 搜索楼层
   * 支持按关键词搜索楼层名称、描述或场馆
   */
  async searchFloors(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { keyword = '', page = 1, limit = 20, venueId, status = FloorStatus.ACTIVE } = req.query;
      const pageNum = parseInt(page as string);
      const limitNum = parseInt(limit as string);
      const skip = (pageNum - 1) * limitNum;

      if (!keyword) {
        return ResponseUtils.sendError(res, { code: 400, message: '搜索关键词不能为空' });
      }

      // 构建搜索条件
      const where: any = {
        status: status as FloorStatus,
        OR: [
          { name: { contains: keyword as string } },
          { description: { contains: keyword as string } },
          { venue: { name: { contains: keyword as string } } }
        ]
      };

      // 如果指定了场馆ID，则按场馆ID筛选
      if (venueId) {
        const venueIdNum = parseInt(venueId as string);
        if (isNaN(venueIdNum)) {
          return ResponseUtils.sendError(res, { code: 400, message: '无效的场馆ID' });
        }
        where.venueId = venueIdNum;
      }

      const [items, total] = await Promise.all([
        prisma.floor.findMany({
          where,
          skip,
          take: limitNum,
          orderBy: [
            { level: 'asc' },
            { name: 'asc' }
          ],
          select: {
            id: true,
            venueId: true,
            venue: {
              select: {
                id: true,
                name: true,
                description: true,
                address: true,
                city: true,
                country: true
              }
            },
            name: true,
            level: true,
            description: true,
            floorPlanUrl: true,
            status: true,
            performances: {
              where: { status: PerformanceStatus.SCHEDULED },
              select: {
                id: true,
                title: true,
                startTime: true,
                endTime: true,
                status: true
              }
            }
          }
        }),
        prisma.floor.count({ where })
      ]);

      // 格式化返回数据
      const formattedItems = items.map((floor) => ({
        ...floor,
        venueId: floor.venueId,
        venue: floor.venue.name,
        performanceCount: floor.performances.length,
        hasActivePerformances: floor.performances.some((p: any) => p.status === PerformanceStatus.SCHEDULED)
      }));

      ResponseUtils.paginated(res, formattedItems, total, pageNum, limitNum, '搜索楼层成功');
    } catch (error) {
      next(error);
    }
  }

  /**
   * 获取场馆楼层统计信息
   * 返回场馆的楼层数量、活跃楼层数量等信息
   */
  async getVenueFloorStats(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { venueId } = req.params;

      if (!venueId) {
        return ResponseUtils.sendError(res, { code: 400, message: '场馆ID不能为空' });
      }

      const venueIdNum = parseInt(venueId);
      if (isNaN(venueIdNum)) {
        return ResponseUtils.sendError(res, { code: 400, message: '无效的场馆ID' });
      }

      // 验证场馆是否存在
      const venue = await prisma.venue.findUnique({
        where: { id: venueIdNum, status: 'ACTIVE' },
        select: {
          id: true,
          name: true
        }
      });

      if (!venue) {
        return ResponseUtils.sendError(res, { code: 404, message: '场馆不存在或已停用' });
      }

      // 获取楼层统计信息
      const [totalFloors, activeFloors, floorsWithPerformances] = await Promise.all([
        prisma.floor.count({
          where: { venueId: venueIdNum }
        }),
        prisma.floor.count({
          where: { 
            venueId: venueIdNum, 
            status: FloorStatus.ACTIVE 
          }
        }),
        prisma.floor.count({
          where: {
            venueId: venueIdNum,
            status: FloorStatus.ACTIVE,
            performances: {
              some: {
                status: PerformanceStatus.SCHEDULED
              }
            }
          }
        })
      ]);

      // 获取楼层层级分布
      const levelDistribution = await prisma.floor.groupBy({
        by: ['level'],
        where: { 
          venueId: venueIdNum, 
          status: FloorStatus.ACTIVE 
        },
        _count: {
          level: true
        },
        orderBy: {
          level: 'asc'
        }
      });

      const stats = {
        venueId: venueIdNum,
        venueName: venue.name,
        totalFloors,
        activeFloors,
        inactiveFloors: totalFloors - activeFloors,
        floorsWithPerformances,
        levelDistribution: levelDistribution.map(item => ({
          level: item.level,
          count: item._count.level
        }))
      };

      ResponseUtils.success(res, stats, '获取场馆楼层统计信息成功');
    } catch (error) {
      next(error);
    }
  }
}
